package com.easylinkin.linkappapi.device.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.easylinkin.linkappapi.common.exceptions.BusinessException;
import com.easylinkin.linkappapi.common.model.RequestModel;
import com.easylinkin.linkappapi.common.utils.DateUtil;
import com.easylinkin.linkappapi.device.constant.DeviceConstant.GrainSize;
import com.easylinkin.linkappapi.device.dao.WaterRecordsMapper;
import com.easylinkin.linkappapi.device.dto.EnvironmentalAreaDTO;
import com.easylinkin.linkappapi.device.dto.EnvironmentalAreaStatisticsDTO;
import com.easylinkin.linkappapi.device.entity.DeviceModel;
import com.easylinkin.linkappapi.device.entity.ElectricyRecords;
import com.easylinkin.linkappapi.device.entity.EnvironmentalArea;
import com.easylinkin.linkappapi.device.entity.WaterRecords;
import com.easylinkin.linkappapi.device.entity.vo.ElectricyRecordsVo;
import com.easylinkin.linkappapi.device.entity.vo.ElectricyStatisticsVo;
import com.easylinkin.linkappapi.device.entity.vo.WaterRecordsVo;
import com.easylinkin.linkappapi.device.entity.vo.WaterStatisticsVo;
import com.easylinkin.linkappapi.device.mapper.DeviceModelMapper;
import com.easylinkin.linkappapi.device.mapper.ElectricyRecordsMapper;
import com.easylinkin.linkappapi.device.mapper.EnvironmentalAreaMapper;
import com.easylinkin.linkappapi.device.service.ElectricyRecordsService;
import com.easylinkin.linkappapi.device.service.EnvironmentalAreaService;
import com.easylinkin.linkappapi.device.service.WaterRecordsService;
import com.easylinkin.linkappapi.lobar.entity.vo.UserStatisticsVo;
import com.easylinkin.linkappapi.lobar.mapper.UserStatisticsMapper;
import com.easylinkin.linkappapi.security.context.LinkappUserContextProducer;
import jodd.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 环境管理区域表 服务实现类
 * </p>
 *
 * @author Xiaoyang
 * @since 2022-09-19
 */
@Service
@Slf4j
public class EnvironmentalAreaServiceImpl extends
    ServiceImpl<EnvironmentalAreaMapper, EnvironmentalArea> implements EnvironmentalAreaService {

  @Resource
  private LinkappUserContextProducer linkappUserContextProducer;

  @Resource
  private DeviceModelMapper deviceModelMapper;

  @Override
  public List<EnvironmentalAreaDTO> queryTree(EnvironmentalAreaDTO environmentalAreaDTO) {
    String tenantId = environmentalAreaDTO.getTenantId();
    if (StringUtils.isBlank(tenantId)){
      tenantId = linkappUserContextProducer.getNotNullCurrent().getTenantId();
    }
    QueryWrapper<EnvironmentalArea> queryWrapper = new QueryWrapper<>();
    //设置查询条件
    queryWrapper.eq("tenant_id_", tenantId)
        .eq("type_", environmentalAreaDTO.getType())
        .orderByAsc("level_", "create_time_");
    List<EnvironmentalArea> areaList = baseMapper.selectList(queryWrapper);
    List<EnvironmentalAreaDTO> areaDTOS = BeanUtil
        .copyToList(areaList, EnvironmentalAreaDTO.class);
    //组织数据
    String finalTenantId = tenantId;
    areaDTOS.stream().forEach(p -> {
      QueryWrapper<DeviceModel> modelQueryWrapper = new QueryWrapper<>();
      //设置查询条件
      modelQueryWrapper.eq("tenant_id", finalTenantId)
          .eq("environmental_area_id", p.getId())
          .eq("model_id_", 0)
          .eq("is_remove_", 0);
      List<DeviceModel> deviceModels = deviceModelMapper.selectList(modelQueryWrapper);
      if (CollectionUtil.isNotEmpty(deviceModels)) {
        p.setDeviceCodes(
            deviceModels.stream().map(DeviceModel::getCode).collect(Collectors.toList()));
      }
    });
    List<EnvironmentalAreaDTO> result = areaDTOS.stream()
        .filter(q -> Integer.valueOf(1).equals(q.getLevel()))
        .collect(Collectors.toList());
    setChildren(result, areaDTOS);
    return result;
  }

  @Override
  public List<EnvironmentalAreaDTO> queryList(EnvironmentalAreaDTO environmentalArea) {
    environmentalArea.setTenantId(linkappUserContextProducer.getNotNullCurrent().getTenantId());
    List<EnvironmentalAreaDTO> environmentalAreaDTOS = baseMapper.selectDeviceByArea(environmentalArea);
    return environmentalAreaDTOS;
  }

  @Override
  @Transactional
  public void addArea(EnvironmentalAreaDTO environmentalArea) {
    if(null == environmentalArea.getParentId()){
      environmentalArea.setParentId(0);
    }
    checkExist(environmentalArea);
    setCodeAndLevel(environmentalArea);
    setBase(environmentalArea);
    save(environmentalArea);
    setFull(environmentalArea);
    setDeviceCodeArea(environmentalArea);
  }

  private void setDeviceCodeArea(EnvironmentalAreaDTO environmentalArea) {
    Integer environmentalAreaId = environmentalArea.getId();
    String tenantId = linkappUserContextProducer.getNotNullCurrent().getTenantId();
    // 删除所有已关联的该区域id
    deviceModelMapper.deleteAreaByAreaId(environmentalAreaId, 0, tenantId);
    // 修改设备所属区域
    List<String> deviceCodes = environmentalArea.getDeviceCodes();
    if (CollectionUtil.isNotEmpty(deviceCodes)) {
      deviceCodes.forEach(p -> {
        DeviceModel deviceModel = deviceModelMapper.findOne(0, tenantId, p);
        if (null != deviceModel) {
          if (null != deviceModel.getEnvironmentalAreaId()) {
            throw new BusinessException("该设备号："+ deviceModel.getCode() +"已有区域");
          } else {
            UpdateWrapper<DeviceModel> updateWrapper = new UpdateWrapper<>();
            updateWrapper.eq("auto_id", deviceModel.getAutoId());
            deviceModel.setEnvironmentalAreaId(environmentalAreaId);
            deviceModelMapper.update(deviceModel, updateWrapper);
          }
        }
      });
    }
  }

  @Override
  @Transactional
  public void updateOne(EnvironmentalAreaDTO environmentalArea) {
    checkExist(environmentalArea);
    //编辑设置全名称和全路径
    setEditFull(environmentalArea);
    //设置基本属性
    setBase(environmentalArea);
    updateById(environmentalArea);
    setDeviceCodeArea(environmentalArea);
  }

  @Override
  public void delBatch(List<Integer> areaIds) {
    String tenantId = linkappUserContextProducer.getNotNullCurrent().getTenantId();
    areaIds.forEach(id ->{
      //查询全部子节点
      QueryWrapper<EnvironmentalArea> queryWrapper = new QueryWrapper<>();
      queryWrapper.like("full_id_","/"+id+"/");
      List<EnvironmentalArea> areaList = baseMapper.selectList(queryWrapper);
      Set<Integer> set = areaList.stream().map(p -> p.getId()).collect(Collectors.toSet());
      if (set.size()>0){
        //查询是否关联设备 并删除
        QueryWrapper<DeviceModel> deviceModelQueryWrapper = new QueryWrapper<>();
        deviceModelQueryWrapper.in("environmental_area_id",set);
        Integer integer1 = deviceModelMapper.selectCount(deviceModelQueryWrapper);
        if (integer1> 0 ){
          set.forEach(p->deviceModelMapper.deleteAreaByAreaId(p,0,tenantId));
//          throw new BusinessException("该区域或下属区域已被使用，无法删除！");
        }
      }
      baseMapper.deleteById(id);
      //删除子节点
      baseMapper.delete(queryWrapper);
    });
  }

  /**
   * 编辑设置全名称和全路径
   */
  private void setEditFull(EnvironmentalAreaDTO environmentalArea) {
    //与旧数据name对比
    EnvironmentalArea old = baseMapper.selectById(environmentalArea.getId());
    if (!environmentalArea.getName().equals(old.getName())) {
      //查询全部子节点
      QueryWrapper<EnvironmentalArea> queryWrapper = new QueryWrapper<>();
      queryWrapper.like("full_id_", "/" + environmentalArea.getId() + "/");
      List<EnvironmentalArea> areaList = baseMapper.selectList(queryWrapper);
      String fullName = old.getFullName();
      int i = fullName.lastIndexOf("/");
      if (i > 0) {
        environmentalArea.setFullName(fullName.substring(0, i + 1) + environmentalArea.getName());
      } else {
        environmentalArea.setFullName(environmentalArea.getName());
      }
      setSonFullName(environmentalArea, areaList);
    }
  }

  /**
   * 校验区域是否存在
   */
  private void checkExist(EnvironmentalAreaDTO environmentalArea) {
    QueryWrapper<EnvironmentalArea> queryWrapper = new QueryWrapper<>();
    //设置判断重复条件
    queryWrapper.eq("parent_id_", environmentalArea.getParentId())
        .eq("name_", environmentalArea.getName())
        .eq("type_", environmentalArea.getType())
        .eq("tenant_id_", linkappUserContextProducer.getNotNullCurrent().getTenantId());
    //编辑的时候存在id
    Optional
        .ofNullable(environmentalArea.getId())
        .ifPresent(id -> queryWrapper.ne("id", environmentalArea.getId()));
    Integer integer = baseMapper.selectCount(queryWrapper);
    if (integer > 0) {
      throw new BusinessException("该区域已存在");
    }
  }

  /**
   * 设置编码
   */
  private void setCodeAndLevel(EnvironmentalAreaDTO environmentalArea) {
    String code = "1";
    Integer level = 1;
    Integer order = 1;
    String tenantId = linkappUserContextProducer.getNotNullCurrent().getTenantId();
    QueryWrapper<EnvironmentalArea> queryWrapper = new QueryWrapper<>();
    queryWrapper.eq("tenant_id_", tenantId)
        .eq("parent_id_", environmentalArea.getParentId())
        .eq("type_", environmentalArea.getType())
        .orderByDesc("order_");
    List<EnvironmentalArea> areas = baseMapper.selectList(queryWrapper);
    if (null != areas && areas.size() > 0) {
      EnvironmentalArea sonArea = areas.get(0);
      level = sonArea.getLevel();
      String areaCode = sonArea.getCode();
      code = areaCode.substring(0, areaCode.lastIndexOf(".") + 1) + (sonArea.getOrder() + 1);
      order = sonArea.getOrder() + 1;
    } else {
      //查询父级
      EnvironmentalArea area = baseMapper.selectById(environmentalArea.getParentId());
      if (null != area) {
        code = area.getCode() + ".1";
        level = area.getLevel() + 1;
      }
    }
    environmentalArea.setCode(code);
    environmentalArea.setLevel(level);
    environmentalArea.setOrder(order);
  }

  /**
   * 设置基本属性
   */
  private void setBase(EnvironmentalAreaDTO environmentalArea) {
    environmentalArea.setModifyTime(new Date());
    environmentalArea.setModifyId(linkappUserContextProducer.getCurrent().getId());
    //没有id就是新增,有就是编辑
    if (null == environmentalArea.getId()) {
      environmentalArea.setCreatorId(linkappUserContextProducer.getCurrent().getId());
      environmentalArea.setCreateTime(new Date());
      environmentalArea.setTenantId(linkappUserContextProducer.getNotNullCurrent().getTenantId());
    }
  }

  /**
   * 设置全名称和全路径
   */
  private void setFull(EnvironmentalAreaDTO environmentalArea) {
    //查找问题类别
    environmentalArea.setFullName(environmentalArea.getName());
    EnvironmentalArea area = baseMapper.selectById(environmentalArea.getParentId());
    if (null == area) {
      environmentalArea.setFullId("/" + environmentalArea.getId() + "/");
    } else {
      environmentalArea.setFullId(area.getFullId() + (environmentalArea.getId() + "") + "/");
      environmentalArea.setFullName(area.getFullName() + "/" + environmentalArea.getName());
    }
    baseMapper.updateById(environmentalArea);
  }

  /**
   * 设置子节点全名称
   */
  private void setSonFullName(EnvironmentalArea parent, List<EnvironmentalArea> areaList) {
    //查询子节点
    List<EnvironmentalArea> sonList = areaList.stream()
        .filter(p -> parent.getId().equals(p.getParentId()))
        .collect(Collectors.toList());
    if (sonList.size() > 0) {
      sonList.forEach(s -> {
        s.setFullName(parent.getFullName() + "/" + s.getName());
        updateById(s);
        setSonFullName(s, areaList);
      });
    }
  }

  /**
   * 设置子节点数据
   */
  private void setChildren(List<EnvironmentalAreaDTO> result, List<EnvironmentalAreaDTO> areaDTOS) {
    result.forEach(r -> {
      List<EnvironmentalAreaDTO> sonList = areaDTOS.stream()
          .filter(q -> r.getId().equals(q.getParentId()))
          .collect(Collectors.toList());
      r.setChildren(sonList);
      if (sonList.size() > 0) {
        setChildren(sonList, areaDTOS);
      }
    });
  }

  @Resource
  private WaterRecordsMapper waterRecordsMapper;

  @Resource
  private ElectricyRecordsMapper electricyRecordsMapper;

  @Resource
  private WaterRecordsService appWaterRecordsService;

  @Resource
  private ElectricyRecordsService electricyRecordsService;

  @Resource
  private UserStatisticsMapper userStatisticsMapper;

  @Override
  public List<EnvironmentalAreaStatisticsDTO> getEnvironmentalAreaStatistics(
      EnvironmentalAreaDTO areaDTO) {
    List<EnvironmentalAreaStatisticsDTO> result = new ArrayList<>();
    areaDTO.setTenantId(linkappUserContextProducer.getNotNullCurrent().getTenantId());
    List<EnvironmentalAreaDTO> environmentalAreaDTOS = baseMapper.selectDeviceByArea(areaDTO);

    if (CollectionUtil.isNotEmpty(environmentalAreaDTOS)) {
      if (areaDTO.getType() == 1) {
        WaterRecordsVo appWaterRecords = new WaterRecordsVo();
        appWaterRecords.setStartTime(areaDTO.getStartTime());
        appWaterRecords.setEndTime(areaDTO.getEndTime());
        appWaterRecords.setTenantId(areaDTO.getTenantId());
        environmentalAreaDTOS.forEach(p -> {
          EnvironmentalAreaStatisticsDTO statisticsDTO = new EnvironmentalAreaStatisticsDTO();
          BeanUtils.copyProperties(p, statisticsDTO);
          Double sumWater = 0d;
          if(StringUtils.isNotEmpty(p.getDeviceCode())){
//            appWaterRecords.setDeviceCode(p.getDeviceCode());
            appWaterRecords.setAreaId(p.getId());
            sumWater = waterRecordsMapper.getSumWaterByTime(appWaterRecords);
            if(null == sumWater){
              sumWater = 0d;
            }
          }
          statisticsDTO.setTotalWater(sumWater);
          result.add(statisticsDTO);
        });
        return result.stream().sorted(Comparator.comparing(EnvironmentalAreaStatisticsDTO::getTotalWater).reversed()).collect(Collectors.toList());
      } else {
        ElectricyRecordsVo electricyRecords = new ElectricyRecordsVo();
        electricyRecords.setStartTime(areaDTO.getStartTime());
        electricyRecords.setEndTime(areaDTO.getEndTime());
        electricyRecords.setTenantId(areaDTO.getTenantId());
        environmentalAreaDTOS.forEach(p -> {
          EnvironmentalAreaStatisticsDTO statisticsDTO = new EnvironmentalAreaStatisticsDTO();
          BeanUtils.copyProperties(p, statisticsDTO);
          Double sumElectricy = 0d;
//          if(StringUtils.isNotEmpty(p.getDeviceCode())){
//            electricyRecords.setDeviceCode(p.getDeviceCode());
          if (null != p.getId()) {
            electricyRecords.setAreaId(p.getId());
            sumElectricy = electricyRecordsMapper.getSumElectricyByTime(electricyRecords);
            if(null == sumElectricy){
              sumElectricy = 0d;
            }
          }
          statisticsDTO.setTotalElectricy(sumElectricy);
          result.add(statisticsDTO);
        });
        return result.stream().sorted(Comparator.comparing(EnvironmentalAreaStatisticsDTO::getTotalElectricy).reversed()).collect(Collectors.toList());
      }
    }
    return result;
  }

  @Override
  public List<EnvironmentalAreaStatisticsDTO> countAreaStatistics(EnvironmentalAreaDTO areaDTO) {
    List<EnvironmentalAreaStatisticsDTO> result = new ArrayList<>();
    areaDTO.setTenantId(linkappUserContextProducer.getNotNullCurrent().getTenantId());
    List<EnvironmentalAreaDTO> environmentalAreaDTOS = baseMapper.selectDeviceByArea(areaDTO);
    if (CollectionUtil.isNotEmpty(environmentalAreaDTOS)) {
      if (areaDTO.getType() == 1) {
        WaterRecordsVo waterRecordsVo = new WaterRecordsVo();
        waterRecordsVo.setGrainSize(GrainSize.DAY);
        waterRecordsVo.setStartTime(areaDTO.getStartTime());
        waterRecordsVo.setEndTime(areaDTO.getEndTime());
        waterRecordsVo.setTenantId(areaDTO.getTenantId());
        environmentalAreaDTOS.forEach(p -> {
          EnvironmentalAreaStatisticsDTO statisticsDTO = new EnvironmentalAreaStatisticsDTO();
          BeanUtils.copyProperties(p, statisticsDTO);
          if(StringUtils.isNotEmpty(p.getDeviceCode())){
//            waterRecordsVo.setDeviceCode(p.getDeviceCode());
            waterRecordsVo.setAreaId(p.getId());
            List<WaterStatisticsVo> record = appWaterRecordsService.getWaterStatisticsList(waterRecordsVo);
            statisticsDTO.setWaterStatisticsList(record);
          }
          result.add(statisticsDTO);
        });
      }else{
        ElectricyRecordsVo electricyRecordsVo = new ElectricyRecordsVo();
        electricyRecordsVo.setGrainSize(GrainSize.DAY);
        electricyRecordsVo.setStartTime(areaDTO.getStartTime());
        electricyRecordsVo.setEndTime(areaDTO.getEndTime());
        electricyRecordsVo.setTenantId(areaDTO.getTenantId());
        environmentalAreaDTOS.forEach(p -> {
          EnvironmentalAreaStatisticsDTO statisticsDTO = new EnvironmentalAreaStatisticsDTO();
          BeanUtils.copyProperties(p, statisticsDTO);
//          if(StringUtils.isNotEmpty(p.getDeviceCode())){
//            electricyRecordsVo.setDeviceCode(p.getDeviceCode());
          if(p.getId()!=null){
            electricyRecordsVo.setAreaId(p.getId());
            List<ElectricyStatisticsVo> record = electricyRecordsService
                .getElectricyStatisticsList(electricyRecordsVo);
            statisticsDTO.setElectricyStatisticsList(record);
          }
          result.add(statisticsDTO);
        });
      }
    }
    return result;
  }

  @Override
  public Page countFirstLevelAreaStatistics(RequestModel<EnvironmentalAreaDTO> requestModel) {
    //获取一级区域的数据
    EnvironmentalAreaDTO areaDTO = requestModel.getCustomQueryParams();
    String tenantId = linkappUserContextProducer.getNotNullCurrent().getTenantId();
    areaDTO.setTenantId(tenantId);
    areaDTO.setLevel(1);
    areaDTO.setIsIncludParent(false);
    areaDTO.setParentId(0);
    List<EnvironmentalAreaDTO> environmentalAreaDTOS = baseMapper.selectDeviceByArea(areaDTO);
    List<EnvironmentalAreaStatisticsDTO> areaStatisticsDTOList = new ArrayList<>();
    if(CollectionUtil.isNotEmpty(environmentalAreaDTOS)) {
      List<Integer> areaIds = environmentalAreaDTOS.stream().map(EnvironmentalAreaDTO::getId).collect(Collectors.toList());
      EnvironmentalAreaDTO param = new EnvironmentalAreaDTO();
      BeanUtils.copyProperties(areaDTO,param);
      param.setAreaIds(areaIds);
      areaStatisticsDTOList = countAreaStatistics(param);
    }
    //因为要进行内存分页
    if (CollectionUtil.isNotEmpty(areaStatisticsDTOList)) {

      //1是用水，2是用电
      if(areaDTO.getType()== 1){
        //获取第一个值不为0的数据
        areaStatisticsDTOList = areaStatisticsDTOList.stream().filter(p -> CollectionUtil.isNotEmpty(p.getWaterStatisticsList())).collect(Collectors.toList());
        if(CollectionUtil.isNotEmpty(areaStatisticsDTOList)){
          Page page = new Page<>();
          long current = requestModel.getPage().getCurrent();
          long size = requestModel.getPage().getSize();
          int start = (int) ((current - 1) * size);
          page.setCurrent(current);
          page.setSize(size);
          page.setTotal(areaStatisticsDTOList.get(0).getWaterStatisticsList().size());
          page.setPages((int) Math.ceil(areaStatisticsDTOList.get(0).getWaterStatisticsList().size() / size));
          //进行数据聚合操作
          List<WaterStatisticsVo> result = new ArrayList<>();
          //第一步，将所有的数据切割成分页的那几天
          if(size!=-1){
            for (EnvironmentalAreaStatisticsDTO areaStatisticsDTO : areaStatisticsDTOList) {
              List<WaterStatisticsVo> waterStatisticsList = areaStatisticsDTO.getWaterStatisticsList();
              if (CollectionUtil.isNotEmpty(waterStatisticsList)) {
                List<WaterStatisticsVo> waterStatisticsDTOS = waterStatisticsList.stream().skip(start).limit(size).collect(Collectors.toList());
                areaStatisticsDTO.setWaterStatisticsList(waterStatisticsDTOS);
              }
            }
          }
          //size取的是日期间隔与传入参数的最小值
          List<WaterStatisticsVo> waterStatisticsList = areaStatisticsDTOList.get(0).getWaterStatisticsList();
          long minSize = CollectionUtil.isNotEmpty(waterStatisticsList)?waterStatisticsList.size():0;
          if (minSize>size){
            if(size!=-1){
              minSize = (int) size;
            }
          }
          //第二步，将所有的数据进行聚合
          for (int i = 0; i < minSize; i++) {
            WaterStatisticsVo sum = new WaterStatisticsVo();
            //处理能源数据
            for (EnvironmentalAreaStatisticsDTO areaStatisticsDTO : areaStatisticsDTOList) {
              waterStatisticsList = areaStatisticsDTO.getWaterStatisticsList();
              if (CollectionUtil.isNotEmpty(waterStatisticsList)) {
                WaterStatisticsVo waterStatisticsVo = waterStatisticsList.get(i);
                if(StringUtil.isEmpty(sum.getDays())){
                  sum.setDays(waterStatisticsVo.getDays());
                }
                if (StringUtil.isEmpty(sum.getRefDate())){
                  sum.setRefDate(waterStatisticsVo.getRefDate());
                }
                if(sum.getTodayWater()==null){
                  sum.setTodayWater(0.0d);
                }
                sum.setTodayWater(sum.getTodayWater()+waterStatisticsVo.getTodayWater());
                sum.setTodayValue(String.format("%.2f", sum.getTodayWater()));
              }
            }
            result.add(sum);
          }
          //处理人数
          //获取当前记录的最大时间与最小时间
          result.sort(Comparator.comparing(WaterStatisticsVo::getDays));
          String startDateStr = result.get(0).getDays();
          String endDateStr = result.get(result.size() - 1).getDays();
          Date startDate = DateUtil.parse(startDateStr, "yyyyMMdd");
          Date endDate = DateUtil.parse(endDateStr, "yyyyMMdd");
          //获取当前时间段内的人数,并算平均值
          List<UserStatisticsVo> userStatistics = userStatisticsMapper.staticAttendance(tenantId, startDate, endDate);
          for (WaterStatisticsVo waterStatisticsVo : result) {
            for (UserStatisticsVo userStatisticsVo : userStatistics) {
              if (waterStatisticsVo.getDays().equals(userStatisticsVo.getRecordTimeStr())) {
                if(userStatisticsVo.getSum()!=null){
                  waterStatisticsVo.setTodayPeople(userStatisticsVo.getSum());
                  waterStatisticsVo.setAvgPeopleWater((userStatisticsVo.getSum()!=null && userStatisticsVo.getSum()!=0)?(waterStatisticsVo.getTodayWater()/Double.valueOf(userStatisticsVo.getSum())):0.0d);
                  waterStatisticsVo.setTodayAvgValue(String.format("%.2f", waterStatisticsVo.getAvgPeopleWater()));
                }else {
                  waterStatisticsVo.setTodayPeople(0);
                  waterStatisticsVo.setAvgPeopleWater(0.0d);
                  waterStatisticsVo.setTodayAvgValue("0.00");
                }
              }
            }
            if (waterStatisticsVo.getTodayPeople() == null) {
              waterStatisticsVo.setTodayPeople(0);
              waterStatisticsVo.setAvgPeopleWater(0.0d);
              waterStatisticsVo.setTodayAvgValue("0.00");
            }
          }
          //填充日均行与汇总行
          WaterStatisticsVo avgDay = result.stream().reduce(new WaterStatisticsVo(),(a, b) -> {
            WaterStatisticsVo sum = new WaterStatisticsVo();
            sum.setDays("日均");
            sum.setRefDate("日均");
            sum.setTodayWater((a.getTodayWater()==null?0:a.getTodayWater()) + (b.getTodayWater()==null?0:b.getTodayWater()));
            sum.setTodayPeople((a.getTodayPeople()==null?0:a.getTodayPeople()) + (b.getTodayPeople()==null?0:b.getTodayPeople()));
            return sum;
          });
          WaterStatisticsVo sumDay = result.stream().reduce(new WaterStatisticsVo(),(a, b) -> {
            WaterStatisticsVo sum = new WaterStatisticsVo();
            sum.setDays("汇总");
            sum.setRefDate("汇总");
            sum.setTodayWater((a.getTodayWater()==null?0:a.getTodayWater()) + (b.getTodayWater()==null?0:b.getTodayWater()));
            sum.setTodayPeople((a.getTodayPeople()==null?0:a.getTodayPeople()) + (b.getTodayPeople()==null?0:b.getTodayPeople()));
            sum.setTodayValue(String.format("%.2f", sum.getTodayWater()));
            sum.setAvgPeopleWater((sum.getTodayPeople()!=null && sum.getTodayPeople()!=0)?(sum.getTodayWater()/sum.getTodayPeople()):0.0d);
            sum.setTodayAvgValue(String.format("%.2f", sum.getAvgPeopleWater()));
            return sum;
          });
          avgDay.setAvgPeopleWater((avgDay.getTodayPeople()!=null && avgDay.getTodayPeople()!=0)?(avgDay.getTodayWater()/avgDay.getTodayPeople()/minSize):0.0d);
          avgDay.setTodayAvgValue(String.format("%.2f", avgDay.getAvgPeopleWater()));
          avgDay.setTodayWater(avgDay.getTodayWater()/minSize);
          avgDay.setTodayValue(String.format("%.2f", avgDay.getTodayWater()));
          avgDay.setTodayPeople((int) Math.round((avgDay.getTodayPeople()*1.0)/minSize));
          result.add(avgDay);
          result.add(sumDay);
          page.setRecords(result);
          return page;
        }
      }else {
        areaStatisticsDTOList = areaStatisticsDTOList.stream().filter(p -> CollectionUtil.isNotEmpty(p.getElectricyStatisticsList())).collect(Collectors.toList());
        if (CollectionUtil.isNotEmpty(areaStatisticsDTOList)){
          Page page = new Page<>();
          long current = requestModel.getPage().getCurrent();
          long size = requestModel.getPage().getSize();
          int start = (int) ((current - 1) * size);
          page.setCurrent(current);
          page.setSize(size);
          page.setTotal(areaStatisticsDTOList.get(0).getElectricyStatisticsList().size());
          page.setPages((int) Math.ceil(areaStatisticsDTOList.get(0).getElectricyStatisticsList().size() / size));
          //进行数据聚合操作
          List<ElectricyStatisticsVo> result = new ArrayList<>();
          //第一步，将所有的数据切割成分页的那几天
          if (size!=-1){
            for (EnvironmentalAreaStatisticsDTO areaStatisticsDTO : areaStatisticsDTOList) {
              List<ElectricyStatisticsVo> electricyStatisticsList = areaStatisticsDTO.getElectricyStatisticsList();
              if (CollectionUtil.isNotEmpty(electricyStatisticsList)) {
                List<ElectricyStatisticsVo> electricyStatisticsVos = electricyStatisticsList.stream().skip(start).limit(size).collect(Collectors.toList());
                areaStatisticsDTO.setElectricyStatisticsList(electricyStatisticsVos);
              }
            }
          }
          //size取的是日期间隔与传入参数的最小值
          List<ElectricyStatisticsVo> electricyStatisticsList = areaStatisticsDTOList.get(0).getElectricyStatisticsList();
          long minSize = CollectionUtil.isNotEmpty(electricyStatisticsList)?electricyStatisticsList.size():0;
          if (minSize>size){
            if(size!=-1){
              minSize = (int) size;
            }
          }
          //第二步，将所有的数据进行聚合
          for (int i = 0; i < minSize; i++) {
            ElectricyStatisticsVo sum = new ElectricyStatisticsVo();
            //处理能源数据
            for (EnvironmentalAreaStatisticsDTO areaStatisticsDTO : areaStatisticsDTOList) {
              electricyStatisticsList = areaStatisticsDTO.getElectricyStatisticsList();
              if (CollectionUtil.isNotEmpty(electricyStatisticsList)) {
                ElectricyStatisticsVo electricyStatisticsVo = electricyStatisticsList.get(i);
                if(StringUtil.isEmpty(sum.getDays())){
                  sum.setDays(electricyStatisticsVo.getDays());
                }
                if (StringUtil.isEmpty(sum.getRefDate())){
                  sum.setRefDate(electricyStatisticsVo.getRefDate());
                }
                if(sum.getTodayElectricy()==null){
                  sum.setTodayElectricy(0.0d);
                }
                sum.setTodayElectricy(sum.getTodayElectricy()+electricyStatisticsVo.getTodayElectricy());
                sum.setTodayValue(String.format("%.2f", sum.getTodayElectricy()));
              }
            }
            result.add(sum);
          }
          //处理人数
          //获取当前记录的最大时间与最小时间
          result.sort(Comparator.comparing(ElectricyStatisticsVo::getDays));
          String startDateStr = result.get(0).getDays();
          String endDateStr = result.get(result.size() - 1).getDays();
          Date startDate = DateUtil.parse(startDateStr, "yyyyMMdd");
          Date endDate = DateUtil.parse(endDateStr, "yyyyMMdd");
          //获取当前时间段内的人数,并算平均值
          List<UserStatisticsVo> userStatistics = userStatisticsMapper.staticAttendance(tenantId, startDate, endDate);
          for (ElectricyStatisticsVo electricyStatisticsVo : result) {
            for (UserStatisticsVo userStatisticsVo : userStatistics) {
              if (electricyStatisticsVo.getDays().equals(userStatisticsVo.getRecordTimeStr())) {
                if(userStatisticsVo.getSum()!=null){
                  electricyStatisticsVo.setTodayPeople(userStatisticsVo.getSum());
                  electricyStatisticsVo.setTodayValue(String.format("%.2f", electricyStatisticsVo.getTodayElectricy()));
                  electricyStatisticsVo.setAvgPeopleElectricy((userStatisticsVo.getSum()!=null && userStatisticsVo.getSum()!=0)?(electricyStatisticsVo.getTodayElectricy()/Double.valueOf(userStatisticsVo.getSum())):0.0d);
                  electricyStatisticsVo.setTodayAvgValue(String.format("%.2f", electricyStatisticsVo.getAvgPeopleElectricy()));
                }else {
                  electricyStatisticsVo.setTodayPeople(0);
                  electricyStatisticsVo.setAvgPeopleElectricy(0.0d);
                  electricyStatisticsVo.setTodayAvgValue("0.00");
                }
              }
            }
            if (electricyStatisticsVo.getTodayPeople()==null){
              electricyStatisticsVo.setTodayPeople(0);
              electricyStatisticsVo.setAvgPeopleElectricy(0.0d);
              electricyStatisticsVo.setTodayAvgValue("0.00");
            }
          }
          //填充日均行与汇总行
          ElectricyStatisticsVo avgDay = result.stream().reduce(new ElectricyStatisticsVo(),(a, b) -> {
            ElectricyStatisticsVo sum = new ElectricyStatisticsVo();
            sum.setDays("日均");
            sum.setRefDate("日均");
            sum.setTodayElectricy((a.getTodayElectricy()==null?0:a.getTodayElectricy()) + (b.getTodayElectricy()==null?0:b.getTodayElectricy()));
            sum.setTodayPeople((a.getTodayPeople()==null?0:a.getTodayPeople()) + (b.getTodayPeople()==null?0:b.getTodayPeople()));
            return sum;
          });
          ElectricyStatisticsVo sumDay = result.stream().reduce(new ElectricyStatisticsVo(),(a, b) -> {
            ElectricyStatisticsVo sum = new ElectricyStatisticsVo();
            sum.setDays("汇总");
            sum.setRefDate("汇总");
            sum.setTodayElectricy((a.getTodayElectricy()==null?0:a.getTodayElectricy()) + (b.getTodayElectricy()==null?0:b.getTodayElectricy()));
            sum.setTodayValue(String.format("%.2f", sum.getTodayElectricy()));
            sum.setTodayPeople((a.getTodayPeople()==null?0:a.getTodayPeople()) + (b.getTodayPeople()==null?0:b.getTodayPeople()));
            sum.setAvgPeopleElectricy((sum.getTodayPeople()!=null && sum.getTodayPeople()!=0)?(sum.getTodayElectricy()/sum.getTodayPeople()):0.0d);
            sum.setTodayAvgValue(String.format("%.2f", sum.getAvgPeopleElectricy()));
            return sum;
          });
          avgDay.setAvgPeopleElectricy((avgDay.getTodayPeople()!=null && avgDay.getTodayPeople()!=0)?(avgDay.getTodayElectricy()/avgDay.getTodayPeople()/minSize):0.0d);
          avgDay.setTodayAvgValue(String.format("%.2f", avgDay.getAvgPeopleElectricy()));
          avgDay.setTodayElectricy(avgDay.getTodayElectricy()/minSize);
          avgDay.setTodayValue(String.format("%.2f", avgDay.getTodayElectricy()));
          avgDay.setTodayPeople((int) Math.round((avgDay.getTodayPeople()*1.0)/minSize));
          result.add(avgDay);
          result.add(sumDay);
          page.setRecords(result);

          return page;
        }
      }
    }
    return null;
  }

  @Override
  public void initData() {
    log.info("--开始导入数据--");
    Map<String,DeviceModel> deviceModelMap = new HashMap<>();
    //查询水表或电表的数据
    List<ElectricyRecords> electricyRecordsList = electricyRecordsService.list();
    List<WaterRecords> waterRecordsList = appWaterRecordsService.list();
    for (ElectricyRecords electricyRecords : electricyRecordsList) {
      //根据设备id查询区域id
      DeviceModel deviceModel = getDeviceModel(deviceModelMap, electricyRecords.getDeviceCode());
      if (deviceModel == null) continue;
      if (deviceModel.getEnvironmentalAreaId()!=null && electricyRecords.getAreaId()==null){
          electricyRecords.setAreaId(deviceModel.getEnvironmentalAreaId());
          electricyRecordsService.updateById(electricyRecords);
      }
    }

    //更新用水记录的区域id
    for (WaterRecords waterRecords : waterRecordsList) {
      //根据设备id查询区域id
      DeviceModel deviceModel = getDeviceModel(deviceModelMap, waterRecords.getDeviceCode());
      if (deviceModel == null) continue;
      if (deviceModel.getEnvironmentalAreaId()!=null && waterRecords.getAreaId()==null){
        waterRecords.setAreaId(deviceModel.getEnvironmentalAreaId());
        appWaterRecordsService.updateById(waterRecords);
      }
    }

    log.info("-----------------导入结束---------------");
  }

  private DeviceModel getDeviceModel(Map<String, DeviceModel> deviceModelMap, String waterRecords) {
    DeviceModel deviceModel = null;
    if (deviceModelMap.get(waterRecords) == null) {
      LambdaQueryWrapper<DeviceModel> deviceModelLambdaQueryWrapper = new LambdaQueryWrapper<>();
      deviceModelLambdaQueryWrapper.eq(DeviceModel::getCode, waterRecords).eq(DeviceModel::getRemoveStatus, 0);
      List deviceModelList = deviceModelMapper.selectList(deviceModelLambdaQueryWrapper);
      if (CollectionUtil.isNotEmpty(deviceModelList)) {
        deviceModel = (DeviceModel) deviceModelList.get(0);
        deviceModelMap.put(waterRecords, deviceModel);
      } else {
        deviceModel = new DeviceModel();
        deviceModelMap.put(waterRecords, deviceModel);
        return null;
      }
    } else {
      deviceModel = deviceModelMap.get(waterRecords);
    }
    return deviceModel;
  }
}
